package controllers

import (
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"news2/cache"
	"news2/models"
	time2 "time"
)

type NewsController struct {
	beego.Controller
}

type Res struct {
	Code    int         `json:"code"`
	Data    interface{} `json:"data"`
	Message string      `json:"message"`
}

func (c *NewsController) Add() {
	title := c.GetString("title")
	time := c.GetString("time")
	types := c.GetString("types")
	if title == "" || time == "" || types == "" {
		c.Data["json"] = Res{
			Code:    500,
			Data:    nil,
			Message: "内容不能为空",
		}
		c.ServeJSON()
		return
	}

	news := models.News{
		Title: title,
		Time:  time,
		Types: types,
	}

	if err := news.GetNewBy(); err != nil {
		c.Data["json"] = Res{
			Code:    500,
			Data:    nil,
			Message: "系统错误",
		}
		c.ServeJSON()
		return
	}

	key := fmt.Sprintf("news_id_%d", news.ID)
	jsonData, _ := json.Marshal(&news)
	cache.Rdb.Set(cache.Ctx, key, jsonData, time2.Hour*24)

	news.Add()
	c.Data["json"] = Res{
		Code:    200,
		Data:    news,
		Message: "新闻信息添加成功",
	}
	c.ServeJSON()
	return
}

func (c *NewsController) List() {
	keyword := c.GetString("keyword")
	page, _ := c.GetInt("page")
	pageSize, _ := c.GetInt("pageSize")
	var news models.News
	var lists []*models.News

	key := fmt.Sprintf("news_list_%s_%d", keyword, page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	if cacheData == "" {
		lists, _ = news.List(keyword, page, pageSize)
		if len(lists) != 0 {
			jsonData, _ := json.Marshal(lists)
			cache.Rdb.Set(cache.Ctx, key, jsonData, time2.Hour*24)
		}
	} else {
		fmt.Println("获取成功")
		json.Unmarshal([]byte(cacheData), &lists)
	}
	c.Data["json"] = Res{
		Code:    200,
		Data:    lists,
		Message: "新闻信息展示成功",
	}
	c.ServeJSON()
	return
}

func (c *NewsController) Update() {
	id, _ := c.GetInt("id")
	title := c.GetString("title")
	time := c.GetString("time")
	types := c.GetString("types")

	news := models.News{
		Title: title,
		Time:  time,
		Types: types,
	}
	news.ID = uint(id)

	if err := news.Update(); err != nil {
		c.Data["json"] = Res{
			Code:    500,
			Data:    nil,
			Message: "系统错误",
		}
		c.ServeJSON()
		return
	}

	key := fmt.Sprintf("news_id_%d", news.ID)
	jsonData, _ := json.Marshal(news)
	cache.Rdb.Set(cache.Ctx, key, jsonData, time2.Hour*24)

	c.Data["json"] = Res{
		Code:    200,
		Data:    news,
		Message: "新闻信息修改成功",
	}
	c.ServeJSON()
	return
}

func (c *NewsController) Del() {
	id, _ := c.GetInt("id")
	var news models.News
	news.ID = uint(id)

	if err := news.Del(); err != nil {
		c.Data["json"] = Res{
			Code:    500,
			Data:    nil,
			Message: "系统错误",
		}
		c.ServeJSON()
		return
	}

	key := fmt.Sprintf("news_id_%d", news.ID)
	cache.Rdb.Del(cache.Ctx, key)
	c.Data["json"] = Res{
		Code:    200,
		Data:    nil,
		Message: "新闻信息删除成功",
	}
	c.ServeJSON()
	return
}
